package org.example.codesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import org.example.codesandbox.model.ExecuteCodeRequest;
import org.example.codesandbox.model.ExecuteCodeResponse;
import org.example.codesandbox.model.JudgeInfo;
import org.example.codesandbox.model.ProcessMessage;
import org.example.codesandbox.utils.ProcessUtils;
import org.omg.CORBA.TIMEOUT;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/*
 *docker实现代码沙箱
 * 将编译文件存入上传到docker中
 * 在docker运行编译文件实现环境隔离
 * */
@Component
public class JavaDockerCodeSanBox extends JavaCodeSandBoxTemplate {

    private static boolean FIRST_INIT = true;

    private static final long TIMEOUT = 5000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        return super.executeCode(executeCodeRequest);
    }

    @Override
    public List<ProcessMessage> runFile(File file, List<String> inputList) {
        //创建docker客户端，用java来操控docker容器
        DockerClient dockerClinet = DockerClientBuilder.getInstance().build();

        //拉取jdk镜像，让容器有java的运行环境
        String image = "openjdk:8-alpine";
        //只执行一次
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClinet.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            FIRST_INIT = false;
        }

        System.out.println("下载完成");


        //创建一个可交互的docker容器 支持多次输入并返回多次结果
        CreateContainerCmd containerCmd = dockerClinet.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(file.getParentFile().getAbsolutePath(), new Volume("/app")));//将编译文件上传到docker的app目录中
        CreateContainerResponse containerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)//设置网络配置关闭
                .withReadonlyRootfs(true)//只读根目录
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println("创建容器成功 " + containerResponse);

        //启动容器,运行代码
        String containerId = containerResponse.getId();//获取到容器id
        dockerClinet.startContainerCmd(containerId).exec();//启动容器
        StopWatch stopWatch = new StopWatch();
        List<ProcessMessage> list = new ArrayList<>();//输入用例得到结果的集合
        for (String input : inputList) {
            ProcessMessage processMessage = new ProcessMessage();
            String[] inputArgs = input.split(" ");//根据空格分割字符串
            System.out.println("输入用例：" + Arrays.toString(inputArgs));
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgs);
            //创建命令
            ExecCreateCmdResponse createCmdResponse = dockerClinet.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("命令创建成功 " + createCmdResponse.toString());

            //执行命令
            String cmdResponseId = createCmdResponse.getId();//创建命令的id
            //执行命令的回调函数
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        processMessage.setErrorMessage(new String(frame.getPayload()));
                        System.out.println("输出错误结果: " + new String(frame.getPayload()));
                    } else {
                        processMessage.setMessage(new String(frame.getPayload()));
                        System.out.println("输出结果: " + new String(frame.getPayload()));
                    }
                    super.onNext(frame);
                }
            };

            //获取占用的内存
            StatsCmd statsCmd = dockerClinet.statsCmd(containerId);
            final long[] maxMemory = {0L};
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
            statsCmd.exec(statisticsResultCallback);
            stopWatch.start();//开始计时

            //开始执行命令运行代码
            try {
                dockerClinet.execStartCmd(cmdResponseId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIMEOUT, TimeUnit.MILLISECONDS);//超时控制
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            stopWatch.stop();//结束计时
            processMessage.setTime(stopWatch.getLastTaskTimeMillis());
            statsCmd.close();//关闭内存监控
            processMessage.setMemory(maxMemory[0]);
            list.add(processMessage);
        }
        return list;
    }
}
